import { AbstractButton, Icon } from "@/components";
import { navigateTo } from "@/utils/navigation";
import { Button, View } from "@tarojs/components";
import style from "./index.module.scss";
import { TouchEvent, useState } from "react";
import { useDidHide } from "@tarojs/taro";
import { ActionNames, sendAction } from "@/utils/tracking";

interface CustomerServiceProps {
  hideCS?: boolean;
  withBottomDock?: boolean;
  cartItemLength?: number;
}

const DEFAULT_DISPLACEMENT_COORDS = {
  x: 0,
  y: 0,
};

const C05CustomerService = ({
  cartItemLength = 0,
  hideCS,
  withBottomDock,
}: CustomerServiceProps) => {
  const [initialTouch, setInitialTouch] = useState(DEFAULT_DISPLACEMENT_COORDS);
  const [dragOffset, setDragOffset] = useState(DEFAULT_DISPLACEMENT_COORDS);

  useDidHide(() => {
    setInitialTouch(DEFAULT_DISPLACEMENT_COORDS);
    setDragOffset(DEFAULT_DISPLACEMENT_COORDS);
  });

  return (
    <View
      className={`${style["customer-service-wrapper"]} ${
        withBottomDock && style["higher"]
      }`}
      onTouchStart={(event) => {
        // @ts-ignore
        const touches = event.touches as TouchEvent;
        const touchLoc = touches[0];
        setInitialTouch({
          x: (touchLoc.clientX as number) - dragOffset.x,
          y: (touchLoc.clientY as number) - dragOffset.y,
        });
      }}
      onTouchMove={(event) => {
        event.stopPropagation();
        // @ts-ignore
        const touches = event.touches as TouchEvent;
        const touchLoc = touches[0];

        setDragOffset({
          x: touchLoc.clientX - initialTouch.x,
          y: touchLoc.clientY - initialTouch.y,
        });
      }}
      style={{
        transform: `translate(${dragOffset.x}px, ${dragOffset.y}px)`,
      }}
    >
      {!!cartItemLength && (
        <View className={style["cart-wrapper"]}>
          <Icon
            type="CartFloating"
            className={style.cart}
            onClick={() => {
              navigateTo("pages/cart/index");
            }}
          />
          <View className={style["cart-count"]}>{cartItemLength}</View>
        </View>
      )}
      {!hideCS && (
        <AbstractButton
          variant="plain"
          className={style["help-wrapper"]}
          openType="contact"
          onClick={() => {
            sendAction(ActionNames.CustomerServiceClick)
          }}
        >
          <Icon type="HelpDeskFloating" className={style.help} />
        </AbstractButton>
      )}
    </View>
  );
};

export default C05CustomerService;
